<template>
  <div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
      <div class="table-page-search-wrapper">
        <a-form :form="searchForm" layout="inline">
          <a-row :gutter="48">
            <SearchFormItems
              :searchKeys="CompanyListSearchKeys"
              :advanceVal="advanced"
              :getDataWithKey="getDataWithKey"
            >
            </SearchFormItems>
            <a-col :md="(!advanced && 8) || 6" :sm="6" class="advanced_butns">
              <span
                class="table-page-search-submitButtons"
                :style="
                  (advanced && { float: 'right', overflow: 'hidden' }) || {}
                "
              >
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="search">查询</a-button>
                <a @click="toggleAdvanced">
                  {{ advanced ? "收起" : "展开" }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div class="cont_box">
      <div class="table_header flex-between">
        <div class="table_name">{{ pageTitle }}</div>
        <div class="table_butns flex-end">
          <a-button type="primary" icon="plus" @click="showModal('add', null)">
            新增
          </a-button>
        </div>
      </div>
      <a-table
        :columns="CompanyListColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it) => it.id"
        :loading="loading"
        binvested
        @change="tableSort"
      >
        <a-badge
          slot="status"
          slot-scope="text"
          :status="text.status == '正常' ? 'success' : 'error'"
          :text="text.status||'禁用'"
        />
        <span slot="operation" slot-scope="text, record">
          <a-button size="small" type="link" @click="statusUpdate(record)">
            {{ text.status == '正常' ? "禁用" : "启用" }}
          </a-button>
          <a-button size="small" type="link" @click="showModal('edit', record)">
            编辑
          </a-button>
        </span>
      </a-table>
      <pagination
        :total="total"
        :page.sync="page"
        :size.sync="size"
        :onPageSizeChange="onPageSizeChange"
      />
      <a-modal
        :title="modalType == 'edit' ? '编辑' : '新增'"
        v-model="editVisible"
        destroyOnClose
        @ok="sureModal"
        width="600px"
      >
        <div class="modal_body_cont">
          <a-form
            :form="modalForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <modalFormItem
              :searchKeys="CompanyModalKeys"
              :getDataWithKey="getDataWithKey"
            ></modalFormItem>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import {
  CompanyListSearchKeys,
  CompanyListColumn,
  CompanyModalKeys,
} from "./config";
import {
  companyList,
  companyUpdate,
  generateFileType,
  companyStatusEnum,

  companyOne,
  companyActive,
} from "@/api/company";

export default {
  name: "CompanyList",
  data() {
    return {
      pageTitle: "",
      CompanyListSearchKeys,
      CompanyListColumn,
      // 高级搜索 展开/关闭
      advanced: false,
      dataSource: [],
      pagination: false,
      page: 1,
      size: 50,
      total: 0,
      loading: false,
      editVisible: false,
      searchForm: this.$form.createForm(this, { name: "company_list_search" }),
      modalForm: this.$form.createForm(this, {
        name: "company_list_modal",
      }),
      CompanyModalKeys,
      companyId: "",
      importLoading: false,
      modalType: "add",
      sortString: "createTime,desc",
      generateFileTypeOpt: [],
      companyStatusEnumOpt: [],
    };
  },
  computed: {
    getDataWithKey() {
      return (key) => {
        switch (key) {
          case "status":
            return this.companyStatusEnumOpt;
          case "fileType":
            return this.generateFileTypeOpt;
          default:
            return [];
        }
      };
    },
  },
  created() {
    this.pageTitle = this.$route?.meta?.title;
    this.getList();
    this.getcompanyStatusEnum();
    this.getgenerateFileType();
  },
  methods: {
    async getgenerateFileType() {
      let result = await generateFileType();
      this.generateFileTypeOpt = result?.data;
    },
    async getcompanyStatusEnum() {
      let result = await companyStatusEnum();
      this.companyStatusEnumOpt = result?.data;
    },
    search() {
      this.page = 1;
      this.getList();
    },
    reset() {
      this.searchForm.resetFields();
      this.page = 1;
      this.getList();
    },
    onPageSizeChange(page, size) {
      this.page = page;
      this.getList(page, size);
    },
    statusUpdate(record) {
      this.$confirm({
        title: `确定要${record.status == "正常" ? "禁用" : "启用"}吗？`,
        content: "",
        okText: `${record.status == "正常" ? "禁用" : "启用"}`,
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          companyActive({
            id: record.id,
            active: record.status == "正常" ? 0 : 1,
          }).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        },
      });
    },
    tableSort(page, filters, { field, order }) {
      if (field == "createTime" || field == "expireDate") {
        this.sortString = order
          ? field + "," + (order == "descend" ? "desc" : "asc")
          : "";
        this.getList(1);
      }
    },
    cameltoLine(value) {
      return value.replace(/([A-Z])/g, "_$1").toLowerCase();
    },
    // 获取列表
    async getList(currentPage, currentSize) {
      this.loading = true;
      const { page, size, sortString } = this;
      let sort = sortString.split(",");
      this.searchForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            pageNum: currentPage || page,
            pageSize: currentSize || size,
            ...values,
            expireDate:
              (values?.expireDate && values?.expireDate.format("YYYY-MM-DD")) ||
              "",
            orders: [
              {
                column: this.cameltoLine(sort[0]),
                asc: sort[1] == "desc" ? false : true,
              },
            ],
          };
          const res = await companyList(params);
          if (res?.success) {
            this.total = res?.data?.total || 0;
            this.dataSource = res?.data?.list || [];
          } else {
            this.$message.error(res?.message);
          }
          this.loading = false;
        } else {
          this.loading = false;
        }
      });
    },
    showModal(type, record) {
      this.modalType = type;
      if (type == "add") {
        this.companyId = "";
        this.modalForm.resetFields();
        this.editVisible = true;
      } else if (type == "edit") {
        companyOne({ id: record.id }).then((res) => {
          if (res.code == 200) {
            this.editVisible = true;
            let { id, name, status, remark, fileType, expireDate } = res.data;
            this.companyId = id;
            this.$nextTick(() => {
              this.modalForm.setFieldsValue({
                name,
                status,
                remark,
                fileType,
                expireDate: moment(expireDate).format("YYYY-MM-DD"),
              });
            });
          } else this.$message.error(res.message);
        });
      }
    },
    sureModal() {
      let { companyId, modalType } = this;
      this.modalForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            ...values,
            id: companyId,
            status: values.status,
          };
          console.log("params>>>", params);
          companyUpdate(params).then((res) => {
            console.log("updatete", res);
            if (res?.success) {
              this.$message.success(
                `${modalType == "add" ? "添加" : "编辑"}成功`
              );
              this.companyId = "";
              this.editVisible = false;
              this.getList();
            } else {
              this.$message.error(res?.message);
            }
          });
        }
      });
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
  },
};
</script>
<style scoped>
:deep(.ant-calendar-picker) {
  width: 100% !important;
}
</style>
